package com.example.softwareconfigurationcoursedesign.LoginRegister;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class QR {
    // 生成二维码的静态方法
    public static void generateQRCode(String data, String filePath, String charset, HashMap hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException {
        BitMatrix matrix;
        // 使用QRCodeWriter类的encode方法生成二维码的BitMatrix对象
        matrix = new QRCodeWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap);
        // 将BitMatrix对象写入到文件中
        MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath.lastIndexOf('.') + 1), new File(filePath));
        System.out.println("QR Code generated successfully at path " + filePath); // 输出生成成功信息
    }

    // 主方法
    public static void main(String[] args) {
        String data ="http://www.moj.gov.cn/" ; // 要编码的数据
        String filePath = "D:\\Desktop\\QR3.png"; // 生成的二维码文件路径

        HashMap hintMap = new HashMap();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 设置纠错级别为L
        hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符集为UTF-8

        try {
            generateQRCode(data, filePath, "UTF-8", hintMap, 200, 200); // 调用生成二维码的方法
        } catch (Exception e) {
            System.out.println("Error creating QR Code: " + e.getMessage()); // 捕获异常并输出错误信息
        }
    }
}